package cn.xz.zgsg.util

import android.content.ContentValues
import android.content.ContentValues.TAG
import android.content.Context
import android.util.Log
import androidx.annotation.Nullable
import cn.xz.zgsg.base.BaseApplication
import cn.xz.zgsg.bean.HttpConfig
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

object DownUtils {

    /**
     * 下载到本地
     * @param context 上下文
     * @param url 网络图
     */
    fun saveImgToLocal(context: Context, url: String, addDowListener: AddDowListener) {
        this.addDowListener = addDowListener
        //如果是网络图片，抠图的结果，需要先保存到本地
        Log.e(TAG, "copyFile11223344: 下载网页链接--1111 ->" + JsonUtil.getUrlName(HttpConfig.BASE_URL_IP + url))
        Log.e(TAG, "copyFile11223344: 下载网页链接 ->" + HttpConfig.BASE_URL_IP + url)

        Glide.with(context)
            .downloadOnly()
            .load(HttpConfig.BASE_URL_IP + url)
            .listener(object : RequestListener<File?> {
                override fun onLoadFailed(
                    @Nullable e: GlideException?,
                    model: Any?,
                    target: Target<File?>?,
                    isFirstResource: Boolean
                ): Boolean {
                    DownUtils.addDowListener?.error()
                    //Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show()
                    Log.e(TAG, "copyFile11223344: 下载失败--1 ->$url")
                    return false
                }

                override fun onResourceReady(
                    resource: File?,
                    model: Any?,
                    target: Target<File?>?,
                    dataSource: com.bumptech.glide.load.DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    var outputUrl = BaseApplication.getContext().cacheDir.absolutePath;

                    val file = File(outputUrl, JsonUtil.getUrlName(HttpConfig.BASE_URL_IP + url))
                    val newImage = file.absolutePath
                    Log.e(TAG, "copyFile11223344: 当前链接--1 ->$newImage")
                    copyFile(resource!!.absolutePath,newImage)
                    return false
                }
            })
            .preload()
    }

    private fun copyFile(oldPathName: String?, newPathName: String?): Boolean {
        return try {
            val oldFile = File(oldPathName)
            if (!oldFile.exists()) {
                Log.e("copyFile", "copyFile:  oldFile not exist.")
                return false
            } else if (!oldFile.isFile) {
                Log.e("copyFile", "copyFile:  oldFile not file.")
                return false
            } else if (!oldFile.canRead()) {
                Log.e("copyFile", "copyFile:  oldFile cannot read.")
                return false
            }
            val fileInputStream = FileInputStream(oldPathName)
            val fileOutputStream = FileOutputStream(newPathName)
            val buffer = ByteArray(1024)
            var byteRead: Int
            while (-1 != fileInputStream.read(buffer).also { byteRead = it }) {
                fileOutputStream.write(buffer, 0, byteRead)
            }
            fileInputStream.close()
            fileOutputStream.flush()
            fileOutputStream.close()
            addDowListener?.success(newPathName.toString())
            Log.e(TAG, "copyFile11223344: 下载成功 new ->$newPathName--old--$oldPathName")
            val ok = Deleteutils.deleteLocal(File(oldPathName)) //删除原文件
            Log.e(ContentValues.TAG, "onCreate: 删除111---->$ok")

            true
        } catch (e: Exception) {
            addDowListener?.error()
            Log.e(TAG, "copyFile11223344: 下载失败--2--->$newPathName")
            e.printStackTrace()
            false
        }
    }

    private var addDowListener: AddDowListener? = null

    interface AddDowListener {
        fun success(url: String)
        fun error()
    }
}